import { Module, MiddlewareConsumer } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DemoController } from './modules/demo/demo.controller';
import { DemoModule } from './modules/demo/demo.module';
import { UserModule } from './modules/user/user.module';
import { TetrisModule } from './modules/tetris/tetris.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LoggerMiddleware } from './common/middleware/logger/logger.middleware';
import { CorsMiddleware } from './common/middleware/cors/cors.middleware';
import { AuthModule } from './modules/auth/auth.module';
import { TalkModule } from './modules/talk/talk.module';
import { ConfigModule } from '@nestjs/config';
import { TalkGateway } from './modules/talk/talk.gateway';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

import * as Joi from 'joi';
import { RoomEntity } from './modules/talk/entities/room.entity';
import { TalkEntity } from './modules/talk/entities/talk.entity';
import { UploadModule } from './modules/upload/upload.module';
import { IconListModule } from './modules/icon-list/icon-list.module';
@Module({
  imports: [
    ConfigModule.forRoot({
      validationSchema: Joi.object({
        DB_HOST: Joi.string().required(),
        DB_PORT: Joi.string().default(5432),
        DB_USERNAME: Joi.string().required(),
        DB_PASSWORD: Joi.string().required(),
        DB_DATABASE: Joi.string().required(),
        JWT_SECRET: Joi.string().required(),
        JWT_TOKEN_AUDIENCE: Joi.string().required(),
        JWT_TOKEN_ISSUER: Joi.string().required(),
        JWT_ACCESS_TOKEN_TTL: Joi.number().default(3600),
      }),
    }),
    // 加载连接数据库
    TypeOrmModule.forRoot({
      type: 'mysql', // 数据库类型
      host: process.env.DB_HOST, // 数据库ip地址
      port: Number(process.env.DB_PORT), // 端口
      username: process.env.DB_USERNAME, // 登录名
      password: process.env.DB_PASSWORD, // 密码
      database: process.env.DB_DATABASE, // 数据库名称
      entities: [__dirname + '/**/*.entity{.ts,.js}'], // 扫描本项目中.entity.ts或者.entity.js的文件
      synchronize: true, // 定义数据库表结构与实体类字段同步(这里一旦数据库少了字段就会自动加入,根据需要来使用)
      autoLoadEntities: true,
    }),
    // 静态文件存放路径
    // ServeStaticModule.forRoot({
    //   rootPath: join(__dirname, 'public'), // 设置静态资源根目录
    //   serveRoot: '/public', // 可选，设置访问静态资源的URL前缀
    // }),
    TypeOrmModule.forFeature([RoomEntity, TalkEntity]),
    DemoModule,
    UserModule,
    AuthModule,
    TalkModule,
    UploadModule,
    IconListModule,
    TetrisModule,
  ],
  controllers: [AppController, DemoController],
  providers: [AppService, TalkGateway],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('/');
    consumer.apply(CorsMiddleware).forRoutes('*'); // 设置需要应用中间件的路由路径，此处为所有路由
  }
}
